package com.yc.tomcat.impl;

import com.sun.net.httpserver.HttpExchange;
import com.yc.tomcat.Cookie;
import com.yc.tomcat.HttpServletRequest;
import com.yc.tomcat.HttpSession;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;


import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpServletRequsetImpl implements HttpServletRequest {

    private InputStream in;
    private String requestURI;
    private String protocol;
    private String method;

    private Map<String,String> headerMap=new HashMap<>();
    //存放参数容器
    private Map<String, List<String>> parameterMap=new HashMap<>();

    private HttpSession session;
    //会话容器
    public static Map<String, HttpSession> sessionMap=new HashMap<>();

    public HttpServletRequsetImpl(Socket socket) throws IOException {
        this.in=socket.getInputStream();

     

     /*   System.out.println(count);
        System.out.println(new String(bytes,0,count));*/
       /* byte [] bytes=new byte[1024];
        int count=in.read(bytes);
        String reqString=new String(bytes,0,count);
        */
        String reqString = readHeader(in);



        String[] lines=reqString.split("\r\n");
        //解析请求头
        for (int i = 0; i < lines.length; i++) {
            if (i==0){
                //请求头行
                String [] items=lines[i].split(" ");
                this.method=items[0];
                this.requestURI=items[1];
                this.protocol=items[2];

                if(this.requestURI.contains("?")){
                    int i1=this.requestURI.indexOf("?");
                    String queryString=this.requestURI.substring(i1+1);
                    System.out.println(queryString);
                //对queryString解码 解决中文编码导致看不懂的问题
                    queryString= URLDecoder.decode(queryString,"utf-8");
                    this.requestURI=this.requestURI.substring(0,i1); //requestURI永远是前面的地址
                    parseParameter(queryString);
                }
            }else if(lines[i].isEmpty()){
                //空行 =》 分隔符
                break;
            }else {
                //请求头
                String[] items=lines[i].split(": ");
                headerMap.put(items[0],items[1]);
            }
        }
        System.out.println(this);
        System.out.println(this.requestURI);
        if("POST".equals(method)){
            parseBody(in);
        }

        //获取或创建会话对象
        Cookie [] cookies=getCookies();
//        HttpSession session=null;
        if(cookies!=null){
            String sessionId=null;
            for (Cookie cookie : cookies) {
                if("JSESSIONID".equals(cookie.getName())){
                    sessionId=cookie.getValue();
                    break;
                }
            }
            if(sessionId!=null){
                session=sessionMap.get(sessionId);
            }
        }
        if (session==null){
            // 第一次 ： 创建会话对象
            session=new HttpSessionImpl();
            // 保存到会话容器中
            sessionMap.put(session.getId(),session);
        }

    }

    //获取请求体数据
    private void parseBody(InputStream in) throws IOException {
        String contentType=headerMap.get("Content-Type");
        if("application/x-www-form-urlencoded".equals(contentType)){
            String length=getHeader("Content-Length");
            long size=Long.parseLong(length);
            StringBuilder buffer=new StringBuilder();
            char c;
            for (int i = 0; i < size; i++) {
                c=(char)in.read();
                buffer.append(c);
            }
            System.out.println("请求体内容：");
            System.out.println(buffer);
            //解析 body中 请求参数
            parseParameter(buffer.toString());
        }if("application/x-www-form-urlencoded".equals(contentType)){
            //文件上传
            //判断长度：低于莫个阀值，保存到内存（StringBuilder),否则保存到磁盘临时文件
            //读取 Content-Type 的分割线，使用分割线切割 请求体
            //分别读取每个字段的值
        }else {
            //TODO
        }

    }
    
    
    
    //获取请求头数据
    private String readHeader(InputStream in)throws IOException{
        StringBuilder buffer=new StringBuilder();
        char c;
        boolean firstEnter=true;
        while (true){
            c=(char)in.read();
            if(c=='\r'){
                buffer.append(c);
                c=(char)in.read();
                buffer.append(c);
                c=(char)in.read();
                if(c=='\r'){
                    buffer.append(c);
                    c=(char)in.read();
                    buffer.append(c);
                    break;
                }
            }
            buffer.append(c);
        }
        return buffer.toString();
    }
    //queryString => a=100&b=abc&a=200  参数部分  ？后面的
    public void parseParameter(String queryString){
        String[] items = queryString.split("&");
        for (String item : items) {  //like.s?like=看电影&like=玩手机&like=打球   //
            String[] nameAndValue = item.split("=");
            String value;
            if(nameAndValue.length==2){
                value=nameAndValue[1];
            }else {
                value="";
            }
            List<String> values=parameterMap.get(nameAndValue[0]);
            //如果values是空，说明是第一次添加参数值
            if(values==null){
                values=new ArrayList<>();
                parameterMap.put(nameAndValue[0],values);

            }
            values.add(nameAndValue[1]);
        }
        System.out.println(parameterMap);
    }

    @Override
    public InputStream getInputStream() {
        return in;
    }

    @Override
    public String getMethod() {

        return method;
    }

    @Override
    public String getRequestURI() {
        return requestURI;
    }

    @Override
    public String getProtocol() {
        return protocol;
    }

    @Override
    public String getHeader(String name) {
        return headerMap.get(name);
    }

    @Override
    public Cookie[] getCookies() {
       String cookie=getHeader("Cookie");
       //Cookie : JSESSIONID=2d42166d-ecdb-41b0-aadb-29c17c306788; c=800
       if(cookie==null){
           return null;
       }
        String[] items = cookie.split("; ");
       List<Cookie> list=new ArrayList<>();
        for (String item : items) {
            String[] nameAndValue = item.split("=");
            Cookie c=new CookieImpl(nameAndValue[0],nameAndValue[1]);
            list.add(c);
        }
        return list.toArray(new Cookie[0]);
    }

    @Override
    public String getRequestedSessionId() {
        return session.getId();
    }



    @Override
    public String getParameter(String name) {
        List<String> values = parameterMap.get(name);
        if(values!=null && values.isEmpty()==false) {
            return values.get(0);
        }
        return null;

    }

    //a=100&a=200&a=300 => getParameterValues("a") =>[100,200,300]
    @Override
    public String[] getParameterValues(String name) {
        List<String> values = parameterMap.get(name);
        if(values==null){
            return null;
        }else {
            return values.toArray(new String[0]);
        }

    }

    @Override
    public String getQueryString() {
        return null;
    }

    @Override
    public HttpSession getSession() {
            return session;
    }

    @Override
    public String toString() {
        return "HttpServletRequsetImpl{" +
                "in=" + in +
                ", requestURI='" + requestURI + '\'' +
                ", protocol='" + protocol + '\'' +
                ", method='" + method + '\'' +
                ", headerMap=" + headerMap +
                '}';
    }
}
